package com.lcy.app.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.alibaba.fastjson.JSONObject;
import com.lcy.app.R;
import com.lcy.app.api.LoginApi;
import com.lcy.app.api.domain.LoginVO;
import com.lcy.app.api.domain.RespEntity;
import com.lcy.app.api.domain.UserCacheInfo;
import com.lcy.app.api.http.HTTP;
import com.lcy.app.common.util.FileUtil;
import com.lcy.app.common.util.HttpUtil;
import com.lcy.app.common.util.StrUtil;
import com.lcy.app.common.util.ToastUtil;

import java.io.File;
import java.util.concurrent.CompletableFuture;

public class MainActivity extends AppCompatActivity {

    public static String token;
    public static UserCacheInfo userCacheInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        // 检查权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            // 如果没有权限，则请求权限
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            CompletableFuture.runAsync(()->{
                System.out.println(getFilesDir());
            });
        }

        // 尝试自动登录
        tryAutoLogin();
    }

    public void login(View view) {
        LoginVO loginVO = new LoginVO();
        EditText usernameText = findViewById(R.id.username);
        loginVO.setUsername(usernameText.getText().toString());
        EditText passwordText = findViewById(R.id.password);
        loginVO.setPassword(passwordText.getText().toString());

        doLogin(loginVO);

        String loginJsonString = JSONObject.toJSONString(loginVO);
        File file = new File(FileUtil.getProjectInnerRootPath(this), "login.json");
        FileUtil.writeFile(file,loginJsonString);
    }

    /**
     * 自动登录
     */
    private void tryAutoLogin() {
        try {
            File loginFile = new File(FileUtil.getProjectInnerRootPath(this), "login.json");
            if (loginFile.exists()) {
                String loginJsonString = FileUtil.readFile(loginFile);
                if (StrUtil.isValidWithoutBlank(loginJsonString)) {
                    LoginVO loginVO = JSONObject.parseObject(loginJsonString, LoginVO.class);
                    if (StrUtil.isValidWithoutBlank(loginVO.getUsername()) &&
                            StrUtil.isValidWithoutBlank(loginVO.getPassword())) {
                        doLogin(loginVO);
                    }
                }
            }
        } catch (Throwable t) {
            ToastUtil.error(this, "自动登录失败，请手动登录");
        }
    }

    private void doLogin(LoginVO loginVO) {
        HTTP<UserCacheInfo> http = new HTTP<>();
        RespEntity<UserCacheInfo> request = http.synRequest(MainActivity.this, retrofit -> retrofit.create(LoginApi.class).login(loginVO));

        if (HttpUtil.isOk(request)) {
            userCacheInfo = request.getData();
            token = "bearer " + userCacheInfo.getToken();

            Intent intent = new Intent(MainActivity.this, MenuActivity.class);
            startActivity(intent);
        }
    }
}
